package edu.caltech.android.power;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.IBinder;

/**
 * Monitor power status (battery charge level, charging, etc). Start this and
 * bind to it.
 * 
 * @author mfaulk
 * 
 */
public class PowerSettings extends Service {
	@SuppressWarnings("unused")
	private static final String TAG = "PowerSettings";

	private final IBinder binder = new PowerSettingsBinder();

	public String batteryStatus;
	public String batteryLevel;

	@Override
	public void onCreate() {
		super.onCreate();

		// register to listen for power events
		this.registerReceiver(this.batteryReceiver, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
	}

	private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub

			if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
				batteryLevel = String.valueOf(arg1.getIntExtra("level", 0)) + "%";
		
				int status = arg1.getIntExtra("status",
						BatteryManager.BATTERY_STATUS_UNKNOWN);
				String strStatus;

				switch(status){
				case BatteryManager.BATTERY_STATUS_CHARGING:
					strStatus = "Charging";
					break;
				case BatteryManager.BATTERY_STATUS_DISCHARGING:
					strStatus = "Discharging";
					break;
				case BatteryManager.BATTERY_STATUS_FULL:
					strStatus = "Full";
					break;
				case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
					strStatus = "Not charging";
					break;
				case BatteryManager.BATTERY_STATUS_UNKNOWN:
					strStatus = "Unknown";
					break;
				default:
					strStatus = "Unknown";
					break;
				}
				batteryStatus = strStatus;
			}
		}
	};

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(batteryReceiver);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	//
	public class PowerSettingsBinder extends Binder {
		public PowerSettings getService() {
			return PowerSettings.this;
		}
	}

}
